var express = require('express');
var router = express.Router();
const bannersService = require("../service/bannersService");
//文件图片上传接口
const multiparty = require("multiparty");//下载插件 npm i multiparty
const path = require('path');//引入上传图片的路径

//新增banner
router.post('/', async function (req, res) {
    let { num, notes, url, status, createTime } = req.body;
    let data = await bannersService.insert({ num, notes, url, status, createTime });
    res.send(data);
})

//根据id删除banner
router.delete('/:id', async function (req, res) {
    let { id } = req.params;
    let data = await bannersService.delete(id);
    res.send(data);
});

//查询所有banner
router.get('/', async function (req, res) {
    let { type, value, current, pageSize } = req.query;
    console.log(req.headers);
    let searchParams = {};
    try {
        if (value) {
            searchParams[type] = new RegExp(value, 'i');
        }
        let data = await bannersService.find({ current: current || 1, pageSize: pageSize || 20 }, searchParams);
        res.send(data);
    } catch (error) {
        console.log(error);
    }
});

//修改banner
router.put('/:id', async function (req, res) {
    let { num, notes, url, status, createTime } = req.body;
    let { id } = req.params;
    let data = await bannersService.update({ num, notes, url, status, createTime, _id: id });
    res.send(data);
})

//上传图片接口 必须是post 
router.post("/upload", function (req, res) {
    var form = new multiparty.Form({ uploadDir: "./public/images/banners" });//在public目录下新建images文件夹用于存放图片的路径
    form.parse(req, function (err, fields, files) {
      //解析图片
      if (err) {
        res.send(err);
      } else {
        console.log("=======")
        console.log(files.file);//上传的文件对象
        var p = files.file[0].path.substring(//0代表对象里面的某一个
          files.file[0].path.indexOf("banners")
        );
        console.log(p)
        res.send({ code: 0, msg: "上传成功",filename:path.basename(p)});
      }
    });
  });

module.exports = router;